//评估记录
import * as React from 'react';
import {
  TreeSelect,
  Modal,
  Row,
  Col,
  DatePicker,
  Menu,
  Steps,
  Dropdown,
  Icon,
  Input,
  Table,
  notification,
  Button,
  Form,
  message,
  InputNumber,
} from 'antd';
import { formatTreeData } from '../../components/commonAips';
import axios from 'axios';
import Api from '../../services/apis';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from "./style.less";

const confirm = Modal.confirm;
//时间组件
const { RangePicker } = DatePicker;
const Step = Steps.Step;
const FormItem = Form.Item;
import moment from 'moment';
import 'moment/locale/zh-cn';
//获取默认时间并在下面转换为moment格式
const nowYear = new Date().getFullYear();
const startTime = `${nowYear}-01-01`;
const [endTimeMonth, endTimeDay] = [
  new Date().getMonth() + 1 < 10 ? `0${new Date().getMonth() + 1}` : new Date().getMonth() + 1,
  new Date().getDate() < 10 ? `0${new Date().getDate()}` : new Date().getDate(),
];
const endTime = `${nowYear}-${endTimeMonth}-${endTimeDay}`;


@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))

class departmentManagement extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      department: '',
      modalVisible: false,
      modifyVisible: false,
      inputValue: ['', '', '', ''],
      newNumber: '',
      newName: '',
      newPassword: '',
      samePassword: '',
      newPhone: '',
      newDepartment: '',
      newArea: '',
      tableData: [],
      current: 1,
      pageSize: 0,
      orgTreeData: [],
      orgId: '',
    };
  }

  //获取表格数据
  sendData = () => {
    const that = this;
    let param = new URLSearchParams();
    param.append('orgName', that.state.department);
    param.append('currentPage', that.state.current);

    console.log(that.state.current);

    axios
      .post(Api.umGetOrganizationList, {
        orgName: that.state.department,
        currentPage: that.state.current,
      })
      .then(function (resp) {
        const {data} = resp;
        if (data && data.length != 0) {
          data.forEach((d, i, arr) => {
            d.key = i;
          });
          that.setState({
            tableData: data,
          });
        }
      });
  };

  componentWillMount() {
    const that = this;

    //获取表格数据
    that.sendData();

    //获取部门树

    axios.post(Api.umGetOrganizationTree, {}).then(function (resp) {
      const {data} = resp;
      if (data) {
        let treeData = new Array(data);
        formatTreeData(treeData, 'orgName', 'orgLevelFormat', 'orgId', 'childOrgList');
        that.setState({ orgTreeData: treeData });
      }
    });
  }

  //查询列表
  query = () => {
    this.setState({ current: 1 }, () => {
      this.sendData();
    });
  };

  //翻页
  pageChange = page => {
    this.setState({ current: page }, () => {
      this.sendData();
    });
  };

  //添加部门
  addOrganization = () => {
    let that = this;
    if (!this.state.inputValue[0]) {
      notification.destroy();
      notification['warning']({
        message: '请填写部门编码！',
      });
    } else if (!this.state.inputValue[1]) {
      notification.destroy();
      notification['warning']({
        message: '请填写部门名称！',
      });
    } else if (!this.state.inputValue[2]) {
      notification.destroy();
      notification['warning']({
        message: '请填写上级部门！',
      });
    } else if (!this.state.inputValue[3]) {
      notification.destroy();
      notification['warning']({
        message: '请填写备注！',
      });
    } else {
      axios
        .post(Api.umAddOrganization, {
          orgCode: this.state.inputValue[0],
          orgName: this.state.inputValue[1],
          parentId: this.state.inputValue[2],
          remark: this.state.inputValue[3],
        })
        .then(function (resp) {
          const {data} = resp;
          if (data.code == 1) {
            notification.destroy();
            notification['success']({
              message: data.msg,
            });
            that.setModalVisible(false);
            that.sendData();
          } else if (data.code == 2) {
            notification.destroy();
            notification['warning']({
              message: data.msg,
            });
          } else if (data.code == 0) {
            notification.destroy();
            notification['error']({
              message: data.msg,
            });
          }
        });
    }
  };

  resetForm() {
    this.setState({
      department: '',
    });
  }

  changeDepartment = e => {
    this.setState({ department: e.target.value });
  };

  changeUser = orgId => {
    //获取部门信息
    const that = this;
    axios
      .post(Api.umGetOrgById, {
        orgId: orgId,
      })
      .then(function (resp) {
        const {data} = resp;
        if (data) {
          that.setState({
            inputValue: [data.orgCode, data.orgName, data.parentId + '', data.remark],
            orgId: orgId,
          });
          that.setState({ modifyVisible: true });
        }
      });
  };

  updateOrganization = () => {
    let that = this;
    if (!this.state.inputValue[0]) {
      notification.destroy();
      notification['warning']({
        message: '请填写部门编码！',
      });
    } else if (!this.state.inputValue[1]) {
      notification.destroy();
      notification['warning']({
        message: '请填写部门名称！',
      });
    } else if (!this.state.inputValue[2]) {
      notification.destroy();
      notification['warning']({
        message: '请填写上级部门！',
      });
    } else if (!this.state.inputValue[3]) {
      notification.destroy();
      notification['warning']({
        message: '请填写备注！',
      });
    } else {
      axios
        .post(Api.umUpdateOrganization, {
          orgId: this.state.orgId,
          orgCode: this.state.inputValue[0],
          orgName: this.state.inputValue[1],
          parentId: this.state.inputValue[2],
          remark: this.state.inputValue[3],
        })
        .then(function (resp) {
          const {data} = resp;
          if (data.code == 1) {
            notification.destroy();
            notification['success']({
              message: data.msg,
            });
            that.setmodifyVisible(false);
            that.sendData();
          } else if (data.code == 2) {
            notification.destroy();
            notification['warning']({
              message: data.msg,
            });
          } else if (data.code == 0) {
            notification.destroy();
            notification['error']({
              message: data.msg,
            });
          }
        });
    }
  };

  setModalVisible(modalVisible) {
    this.setState({
      modalVisible: modalVisible,
      inputValue: ['', '', '', ''],
      orgId: '',
    });
  }

  setmodifyVisible(modifyVisible) {
    this.setState({
      modifyVisible: modifyVisible,
    });
  }

  addNumber = (e, id) => {
    let _inputValue = this.state.inputValue;
    if (typeof e == 'object') {
      _inputValue[id] = e.target.value;
    } else {
      _inputValue[id] = e;
    }
    this.setState({ inputValue: _inputValue });
  };
  modifyNumber = (e, id) => {
    let _modifyValue = this.state.modifyValue;
    _modifyValue[id] = e.target.value;
    this.setState({ modifyValue: _modifyValue });
  };

  render() {
    let that = this;
    const {
      currentUserLoading,
    } = this.props;
    //表头
    const columns = [
      {
        title: '组织机构编号',
        dataIndex: 'orgCode',
        key: 'orgCode',
      },
      {
        title: '组织机构',
        dataIndex: 'orgName',
        key: 'orgName',
      },
      {
        title: '上级部门ID',
        dataIndex: 'parentId',
        key: 'parentId',
      },
      {
        title: '上级部门名称',
        dataIndex: 'parentOrgName',
        key: 'parentOrgName',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, item, index) => (
          <div>
            <a href="javascript:;"
              onClick={() => {
                that.changeUser(item.orgId);
              }}
            >
              修改
            </a>
          </div>
        ),
      },
    ];

    const treeData = [
      {
        title: 'Node1',
        value: '0-0',
        key: '0-0',
        children: [
          {
            title: 'Child Node1',
            value: '0-0-1',
            key: '0-0-1',
          },
          {
            title: 'Child Node2',
            value: '0-0-2',
            key: '0-0-2',
          },
        ],
      },
      {
        title: 'Node2',
        value: '0-1',
        key: '0-1',
      },
    ];

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className='mainContainer'>
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>部门管理</p>
              <p>DEPARTMENT MANAGEMENT</p>
            </div>
          </div>

          <div className='mrb15'>
            <Form layout='inline' align='center'>
              <FormItem>
                <span className="label">部门名称：</span>
                <Input
                  value={this.state.department}
                  data-inp="zdbh"
                  onChange={this.changeDepartment}
                  placeholder="请输入工号"
                />
              </FormItem>
              <Row gutter={24} style={{ textAlign: 'center'}}>
                    <Button icon='search' type="primary" onClick={this.query.bind(this)}>
                      搜索
                    </Button>
                    &emsp;
                    <Button
                      onClick={this.resetForm.bind(this)}
                      type="primary"
                      htmlType="reset"
                      icon="reload"
                    >
                      重置
                  </Button>
                  &emsp;
                  <Button
                    type="primary"
                    onClick={() => this.setModalVisible(true)}
                    htmlType="reset"  icon="plus-circle"
                  >
                    新增
                </Button>
              </Row>
            </Form>
          </div>

          <Row className="choicedBox">
            <Table
              bordered={true}
              scroll={{x:true}}
              align={'center'}
              columns={columns}
              dataSource={this.state.tableData}
            />
          </Row>

          <Modal
            title="基本信息"
            wrapClassName="vertical-center-modal"
            visible={this.state.modalVisible}
            onOk={() => this.addOrganization()}
            onCancel={() => this.setModalVisible(false)}
            width={830}
          >
            <Row gutter={24} className={styles.modalForm}>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>部门编码
              </span>
                <Input
                  value={this.state.inputValue[0]}
                  data-inp="zdbh"
                  onChange={e => {
                    that.addNumber(e, 0);
                  }}
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>部门名称
              </span>
                <Input
                  value={this.state.inputValue[1]}
                  onChange={e => {
                    that.addNumber(e, 1);
                  }}
                  data-inp="zldz"
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>上级部门
              </span>
                <TreeSelect
                  value={this.state.inputValue[2]}
                  treeData={this.state.orgTreeData}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  allowClear
                  treeDefaultExpandedKeys={['1']}
                  onChange={value => that.addNumber(value, 2)}
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>备注
              </span>
                <Input
                  value={this.state.inputValue[3]}
                  onChange={e => {
                    that.addNumber(e, 3);
                  }}
                  data-inp="zldz"
                  placeholder=""
                />
              </Col>
            </Row>
          </Modal>

          <Modal
            title="基本信息"
            wrapClassName="vertical-center-modal"
            visible={this.state.modifyVisible}
            onOk={() => this.updateOrganization()}
            onCancel={() => this.setmodifyVisible(false)}
            width={830}
          >
            <Row gutter={24} className={styles.modalForm}>
            <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>部门编码
              </span>
                <Input
                  value={this.state.inputValue[0]}
                  data-inp="zdbh"
                  onChange={e => {
                    that.addNumber(e, 0);
                  }}
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>部门名称
              </span>
                <Input
                  value={this.state.inputValue[1]}
                  onChange={e => {
                    that.addNumber(e, 1);
                  }}
                  data-inp="zldz"
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>上级部门
              </span>
                <TreeSelect
                  style={{ width: 300 }}
                  value={this.state.inputValue[2]}
                  treeData={this.state.orgTreeData}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder=""
                  allowClear
                  treeDefaultExpandedKeys={['1']}
                  onChange={value => that.addNumber(value, 2)}
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>备注
              </span>
                <Input
                  value={this.state.inputValue[3]}
                  onChange={e => {
                    that.addNumber(e, 3);
                  }}
                  data-inp="zldz"
                  placeholder=""
                />
              </Col>
            </Row>
          </Modal>
        </div>
      </PageHeaderWrapper>
    );
  }
}

export default departmentManagement;
